package com.rgz.utils;



import net.sf.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.rgz.pojo.weixin.AccessToken;
import com.rgz.pojo.weixin.Menu;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.SecureRandom;

/**
 * Created by jackiechan on 2018/1/31/下午8:30
 */
public class WeiXinUtil {

    public static final String APPID = "wx4212554056747263";
    public static final String APPSECRET = "5d0178978087b150666e509b56fb5e03";

    private static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    private static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式
     * @param outPutString 发送的数据
     * @return
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outPutString) {
        JSONObject jsonObject = null;
        StringBuffer stringBuffer = new StringBuffer();
        
        try {
            TrustManager[] tms = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null,tms,new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();

            //创建请求
            URL url=new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(socketFactory);
            connection.setDoOutput(true);//注意 POST 请求方式下不设置这个属性无法发送数据
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);//注意请求方式是大写
            if ("GET".equalsIgnoreCase(requestMethod)) {

                connection.connect();
            }
            if (outPutString != null) {
                //发送数据
                OutputStream os = connection.getOutputStream();
                os.write(outPutString.getBytes("UTF-8"));
                os.close();

            }

            //判断返回的 code
            //此处略过
            InputStream inputStream = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            String resut = null;
            while ((resut = bufferedReader.readLine()) != null) {
                stringBuffer.append(resut);
            }

            bufferedReader.close();
            inputStream.close();

            connection.disconnect();
          jsonObject=  JSONObject.fromObject(stringBuffer.toString());
        }catch (Exception e){
           e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取 accesstoken
     * @param appid
     * @param appScret
     * @return
     */

    public static AccessToken getAccessToken(String appid, String appScret) {
        AccessToken accessToken = null;
         String url = access_token_url.replace("APPID", appid).replace("APPSECRET", appScret);

        JSONObject jsonObject = httpRequest(url, "GET", null);//封装有 accesstoken 的对象

        if (jsonObject != null) {

            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));

            }catch (Exception e){
               e.printStackTrace();
               System.out.println("获取 TOKEN 失败");
            }
        }
        return accessToken;
    }

    /**
     * 创建菜单
     * @param menu
     * @param access_token
     * @return
     */
    public static int createMenu(Menu menu, String access_token) {
        int result = 0;
        String url = menu_create_url.replace("ACCESS_TOKEN", access_token);//创建菜单的地址
        String json = JSONObject.fromObject(menu).toString();//菜单的 json 字符串
      /*  System.out.println(json);*/
        JSONObject jsonObject = httpRequest(url, "POST", json);
        if (jsonObject != null) {
            result = jsonObject.getInt("errcode");
            if (result != 0) {
                System.out.println("创建菜单失败==="+jsonObject.getString("errmsg"));
            }
        }

        return result;
    }
}
